import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo1_Driver_Manager {
    public static void main(String[] args) throws SQLException {
       // DriverManager
        //通过完全限定名加载指定的类到JVM
        Connection connection=null;
        Statement statement=null;//执行静态输入，存在sql注入问题
        PreparedStatement preparedStatement=null;//可解决sql注入问题
        ResultSet resultSet=null;
        try {
            //1.加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "123456");//物理连接
            //3.创建Statement
            statement = connection.createStatement();
            //4.定义SQL并执行SQL语句
            System.out.println("请输入学生姓名：");
            Scanner scanner=new Scanner(System.in);
            //接收用户输入
            String name=scanner.nextLine();
            String sql="select student_id,sn,name from student where name = '" + name +"'";
            //5.获取查询结果
            resultSet = statement.executeQuery(sql);//执行查询
//statement.executeUpdate(sql);//执行更新语句如update
            //6.对结果集进行遍历,迭代
            //如果下一条有记录返回true，反之为false
            while (resultSet.next()){
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                System.out.println(MessageFormat.format("学生编号={0},学生学号={1},学生姓名={2}",stuId,stuSn,stuName));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //依次释放资源，关闭链接
            if(resultSet!=null){
                resultSet.close();
            }
            if(statement!=null){
                statement.close();
            }
            if(connection!=null){
                connection.close();
            }
        }
    }
}
